<template>
  <el-container class="home_container">
    <el-header>
      <div class="home_title">代练管理平台</div>
      <div class="home_userinfoContainer">
        <el-dropdown @command="handleCommand">
  <span class="el-dropdown-link home_userinfo">
    {{currentUserName}}<i class="el-icon-arrow-down el-icon--right home_userinfo"></i>
  </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="sysMsg">修改密码</el-dropdown-item>
            <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-header>
    <el-container>
      <el-aside width="200px">
        <el-menu :unique-opened="true" style="background-color: #ECECEC" router>
          <template v-for="(item,index) in routes" v-if="!item.hidden">
            <el-submenu :index="index+''" v-if="item.children.length>1" :key="index">
              <template slot="title">
                <i :class="item.icon"></i>
                <span style="font-size:16px;">{{item.name}}</span>
              </template>
              <el-menu-item v-for="child in item.children" v-if="!child.hidden" :index="child.path" :key="child.path">
                <!--                {{child.name}}-->
                <i :class="child.icon"></i>
                <span slot="title" style="font-size:14px;">{{child.name}}</span>
              </el-menu-item>
            </el-submenu>
            <template v-else>
              <el-menu-item :index="item.children[0].path">
                <i :class="item.children[0].icon"></i>
                <span slot="title" style="font-size:16px;">{{item.children[0].name}}</span>
              </el-menu-item>
            </template>
          </template>
        </el-menu>
      </el-aside>
      <el-container>
        <el-main>
          <keep-alive>
            <router-view v-if="this.$route.meta.keepAlive"></router-view>
          </keep-alive>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog :visible="showUpdatePasswordDialog" width="450px" @close="showUpdatePasswordDialog = false"
               :close-on-click-modal="false">
      <div slot="title" style="text-align: left;font-size: 20px;">修改密码</div>

      <el-form ref="ruleForm" label-position="left" label-width="100px" :model="formData" :rules="rules">
        <el-form-item label="旧密码：" prop="old_password">
          <el-input v-model.trim="formData.old_password" type="password" style="width:300px;" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="new_password">
          <el-input v-model.trim="formData.new_password" type="password" style="width:300px;" maxlength="16"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="showUpdatePasswordDialog = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>
<script>
    import api from '../utils/api'

    export default {
        name: 'Home',
        data() {

            const validatePassword = (rule, value, callback) => {
                if (value == null || value == '') {
                    callback(new Error('请输入旧密码'));
                } else {
                    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                    if (!reg.test(value)) {
                        callback(new Error('请输入长度6~16位且由字母和数字组成的密码'));
                    } else {
                        callback();
                    }
                }
            };

            const validateNewPassword = (rule, value, callback) => {
                if (value == null || value == '') {
                    callback(new Error('请输入新密码'));
                } else {
                    var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                    if (!reg.test(value)) {
                        callback(new Error('请输入长度6~16位且由字母和数字组成的密码'));
                    } else {
                        let that = this;
                        if (that.formData.old_password == that.formData.new_password) {
                            callback(new Error('新旧密码一致，请更改新密码'));
                        } else {
                            callback();
                        }
                    }
                }
            };

            return {
                routes: [],//路由，控制左侧菜单栏
                currentUserName: '',//当前用户
                showUpdatePasswordDialog: false,//修改密码弹框
                formData: {
                    id: null,
                    old_password: '',
                    new_password: ''
                },
                rules: {
                    old_password: [
                        {validator: validatePassword, trigger: 'change'}
                    ],
                    new_password: [
                        {validator: validateNewPassword, trigger: 'change'}
                    ],
                },
            }
        },
        methods: {
            handleCommand(command) {
                var that = this;
                if (command == 'logout') {
                    this.$confirm('注销登录吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(function () {
                        // location.replace('');
                        api.ajax.get("/logout").then(function (result) {
                            location.replace('');//具备刷新页面效果，用户权限更改菜单会生效
                            // that.$router.replace({path: '/'});//BUG：取消掉的原有的菜单依旧会保留
                        }, function (result) {
                            that.$alert("退出登录失败", '失败!');
                        });
                    }, function () {
                        //取消
                    })
                } else if (command == 'sysMsg') {
                    //修改密码
                    this.showUpdatePasswordDialog = true;
                }
            },
            //保存密码
            save() {
                var that = this;
                this.$refs["ruleForm"].validate((valid) => {
                    if (valid) {
                        var loginUserInfo = JSON.parse(localStorage.getItem("loginUserInfo"));
                        that.formData.id = loginUserInfo.id;
                        api.ajax.put('user/password', that.formData)
                            .then((result) => {
                                if (result.status == 200) {
                                    that.$message.success('修改密码成功，2秒后将自动登出');
                                    that.showUpdatePasswordDialog = false;
                                    setTimeout(() => {
                                        location.replace('');
                                    }, 2000)
                                } else {
                                    that.$message(result.msg);
                                }
                            }, (result) => {
                                that.$alert("修改密码异常", '失败!');
                            })
                    }
                })
            }
        },
        mounted() {
        },
        created: function () {
            var that = this;
            var loginUserInfo = JSON.parse(localStorage.getItem("loginUserInfo"));

            that.routes = that.$router.options.routes;

            that.currentUserName = loginUserInfo.nick_name;
            that.$nextTick(() => {
                //根据登录用户角色配置模块显示隐藏
                api.ajax.get("/user/getUserModules?userName=" + loginUserInfo.user_name).then(function (result) {
                    if (result.status == 200) {
                        var routes = that.$router.options.routes;
                        // //主页显示
                        // routes[1].hiddens = false;
                        var modules = result.data;
                        if (modules.length === 0) {
                            that.$alert('资源异常', '获取用户资源信息失败!');
                            return;
                        }
                        //先整合数据库该用户的权限树
                        var newModules = [];
                        for (let i = 0; i < modules.length; i++) {
                            //依赖父节点组合主子模块
                            if (modules[i].parent_id === null) {
                                var children = [];
                                for (let j = 0; j < modules.length; j++) {
                                    //子接单
                                    if (modules[j].parent_id !== null) {
                                        //显示子菜单集合
                                        if (modules[i].module_id === modules[j].parent_id) {
                                            children.push(modules[j].module_url);
                                        }
                                    }
                                }
                                modules[i].hidden = children.length <= 0;
                                if (children.length > 0) modules[i].children = children;
                                newModules.push(modules[i]);

                            }
                        }
                        //路由和用户权限树匹配
                        for (let k = 0; k < routes.length; k++) {
                            for (let m = 0; m < newModules.length; m++) {
                                //显示主模块
                                if (routes[k].path === newModules[m].module_url && !newModules[m].hidden) {
                                    if (newModules[m].children) {
                                        if (newModules[m].children.length > 0) {
                                            routes[k].hidden = false;
                                            //子模块操作
                                            if (routes[k].children) {
                                                for (let x = 0; x < routes[k].children.length; x++) {
                                                    for (let n = 0; n < newModules[m].children.length; n++) {
                                                        if (routes[k].children[x].path === newModules[m].children[n]) {
                                                            routes[k].children[x].hidden = false;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        that.routes = routes;
                    }

                });
            }, function (result) {
                that.$alert(result.msg, '获取用户资源信息失败!');
            });

        },
    }
</script>
<style>
  .home_container {
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
  }

  .el-header {
    background-color: #20a0ff;
    color: #333;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .el-aside {
    background-color: #ECECEC;
  }

  .el-main {
    background-color: #fff;
    color: #000;
    text-align: center;
  }

  .home_title {
    color: #fff;
    font-size: 22px;
    display: inline;
  }

  .home_userinfo {
    color: #fff;
    cursor: pointer;
  }

  .home_userinfoContainer {
    display: inline;
    margin-right: 20px;
  }
</style>
